package thread;

import java.util.Random;

public class ArraySumWithThreads {
    private static final int ARRAY_LENGTH = 10_000_000;
    private static int[] array;
    private static long evenSum = 0;
    private static long oddSum = 0;

    public static void main(String[] args) throws InterruptedException {
        // 初始化数组
        initializeArray();

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 创建并启动线程
        Thread evenThread = new Thread(new EvenIndexSummer());
        Thread oddThread = new Thread(new OddIndexSummer());
        evenThread.start();
        oddThread.start();

        // 等待两个线程执行完毕
        evenThread.join();
        oddThread.join();

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算总时间
        long totalTime = endTime - startTime;

        // 计算总和
        long totalSum = evenSum + oddSum;

        System.out.println("偶数下标元素的和: " + evenSum);
        System.out.println("奇数下标元素的和: " + oddSum);
        System.out.println("数组所有元素的总和: " + totalSum);
        System.out.println("程序执行时间: " + totalTime + " 毫秒");
    }

    // 初始化数组
    private static void initializeArray() {
        array = new int[ARRAY_LENGTH];
        Random random = new Random();
        for (int i = 0; i < ARRAY_LENGTH; i++) {
            array[i] = random.nextInt(100) + 1;
        }
    }

    // 偶数下标求和线程
    static class EvenIndexSummer implements Runnable {
        @Override
        public void run() {
            long sum = 0;
            for (int i = 0; i < array.length; i += 2) {
                sum += array[i];
            }
            // 使用 synchronized 保证线程安全
            synchronized (ArraySumWithThreads.class) {
                evenSum = sum;
            }
        }
    }

    // 奇数下标求和线程
    static class OddIndexSummer implements Runnable {
        @Override
        public void run() {
            long sum = 0;
            for (int i = 1; i < array.length; i += 2) {
                sum += array[i];
            }
            // 使用 synchronized 保证线程安全
            synchronized (ArraySumWithThreads.class) {
                oddSum = sum;
            }
        }
    }
}